<template>
  <BasicModal title="会员更新" @register="registerModal" @ok="handleSubmit"
    :width="500"  :canFullscreen="false" :centered="true" :destroyOnClose="true"
    :bodyStyle="{height:'calc(100vh - 250px)', overflow:'hidden'}"
  >
    <a-row type="flex" :gutter="5" style="margin: 0; padding: 0">
      <a-col flex="1" style="padding-top: 10px; margin-left: 5px">
        <a-form ref="registerForm" :model="model" :rules="validatorRules" :labelCol="{ span: 5 }" :wrapperCol="{ span: 19 }">
          <a-form-item name="name" label="会员姓名">
            <a-input type="text" aria-valuemax="20" class="formText" v-model:value="model.name" style="width: 230px" :disabled="false" />
            <a-badge :count="count" :number-style="{ backgroundColor: '#52c41a' }" >
              <a-button type="primary" @click="customerInfo(false)" class="ml-2" size="small" style="height: 30px; background-color: orangered;">刷新</a-button>
            </a-badge>
          </a-form-item>
          <a-form-item name="tel" label="手机号码" :wrapperCol="{ span: 19 }">
            <a-input v-model:value="model.tel" class="formText" style="width: 230px" :disabled="false" />
          </a-form-item>
          <a-form-item name="type" label="会员类型" :wrapperCol="{ span: 19 }">
            <JDictSelectTag
              v-model:value="model.type"
              dictCode="memberType"
              :maxTagCount="0"
              :getPopupContainer="(node) => node.parentNode"
              :dropdownStyle="{ width: '150px', overflow: 'auto' }"
              :dropdownMatchSelectWidth="false"
              :styler="{width: '230px'}"
              @select="changeModelType"
            />
          </a-form-item>
          <a-form-item name="corpName" label="会员区域" :wrapperCol="{ span: 19 }" >
            <div readonly style="width: 230px; height: 30px; line-height: 30px; font-size: 18px; border: 1px #d9d9d9 solid; float: left; padding-left: 3px;" :disabled="true">{{ model.areaName }}</div>
            <a-button type="primary" @click="handleCompanySearch" class="ml-2" size="small" style="height: 30px; background-color: orangered;">查找</a-button>
          </a-form-item>
          <a-form-item name="corpName" label="会员单位" :wrapperCol="{ span: 19 }">
            <a-form-item-rest>
              <a-input type="hidden" placeholder="model.id" v-model:value="model.id" />
              <a-input type="hidden" placeholder="model.areaCode" v-model:value="model.areaCode" />
              <a-input type="hidden" placeholder="model.customerId" v-model:value="model.customerId" />
              <a-input type="hidden" placeholder="model.customerTel" v-model:value="model.customerTel" />
              <a-input type="hidden" placeholder="model.areaCode" v-model:value="model.path" />
              <a-input type="hidden" placeholder="model.pathName" v-model:value="model.pathName" />
            </a-form-item-rest>
            <a-select v-if="model.type == 3"
              v-model:value="model.areaCode" 
              style="width: 300px" 
              :options="customerList"
              @select="(val, option) => {
                changeModelAreaCode(val, option);
              }"
            >
            </a-select>
            <div readonly style="width: calc(100% - 50px); font-size: 18px; padding-left: 3px;" :disabled="true" v-else>{{ model.corpName || '未匹配客户信息'}}</div>
          </a-form-item>
          <a-form-item label="会员部门" :wrapperCol="{ span: 7 }" v-show="model.departName != '' && model.type != '3'">
            <div readonly style="width: calc(100% - 50px); font-size: 18px;" :disabled="true">{{ model.departName }}</div>
          </a-form-item>
          <a-form-item label="会员状态" :wrapperCol="{ span: 19 }">
            <a-select v-model:value="model.state" style="width: 150px" :disabled="true">
              <a-select-option value="0">待审核</a-select-option>
              <a-select-option value="1">已审核</a-select-option>
              <a-select-option value="2">已禁用</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="客服账号" :wrapperCol="{ span: 19 }" v-if="model.type == 2">
            <JDictSelectTag
              v-model:value="model.userId"
              dictCode="sys_user,realname,id@authSkr"
              placeholder="全部"
              defaultValue=""
              :multiple="false"
              :showArrow="true"
              :maxTagCount="0"
              :dropdownStyle="{ width: '150px', overflow: 'auto' }"
              :dropdownMatchSelectWidth="false"
              :allowClear="true"
              :showSearch="true"
              :styler="{width: '150px'}"
              :getPopupContainer="triggerNode => triggerNode.parentElement"
              :filterOption="false"
            />
          </a-form-item>
          <a-form-item label="收客人昵称" :wrapperCol="{ span: 19 }" v-show="model.type == 2">
            <a-input v-model:value="model.skrName" class="formText" style="width: 230px" autocomplete="off" />
          </a-form-item>
          <a-form-item label="微信二维码" :wrapperCol="{ span: 19 }" v-show="model.type == 2">
            <JImageUpload bizPath="qrcode" :fileMax="1" v-model:value="model.skrQrcode"></JImageUpload>
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
  </BasicModal>

  <CompanyModal @register="registerCompanyModal" @setSearch="setSearch"></CompanyModal>
  <CustomerModal @register="registerCustomerModal" @setSearch="setSearch"></CustomerModal>
</template>

<script lang="ts" name="MemberAudit" setup>
  import { ref, computed, unref, reactive, onMounted, nextTick } from 'vue';
  import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { auditPc, update, memberUpdate, setCustomerInfo } from '/@/views/weixin/member/member.api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from "/@/components/Modal";
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import JDictSelectTag from "/@/components/Form/src/jeecg/components/JDictSelectTag.vue";
  import CompanyModal from '/@/views/weixin/member/modules/CompanyModal.vue';
  import CustomerModal from '/@/views/weixin/member/modules/CustomerModal.vue';

  // ---------------------------------------------------------------------
  // 定义变量
  const $message = useMessage();
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  // 表单modal
  const registerForm = ref();
  // 疑似重复数据数量
  const count = ref(0);
  // 可操作的model对象
  const model = reactive<any>({});
  // 定义 searchParams
  const customerList = ref<any>([    
    {value: '1100000000000000022,1100000000000001016,', label: '广西客户|广西红马国旅（个人）'},
    {value: '1100000000000000022,1100000000000002596,', label: '广西客户|广西红马国旅（领队）'},
  ]);
  // 表单校验规则
  const validatorRules = {
    corpName: [{ required: true, message: '请选择单位名称!', trigger: 'blur' }],
    name: [{ required: true, message: '不能为空!' }],
    tel: [{ required: true, message: '不能为空!' }],
    type: [{ required: true, message: '不能为空!' }],
  };
  // 定义变量
  // ---------------------------------------------------------------------

  // 表单赋值---------------------------------------
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    // 使用 Object.keys 和 forEach 清空 model 数据
    setModalProps({ confirmLoading: false });

    await auditPc(data).then((res) => {
      nextTick(() => {
        Object.keys(model).forEach((key) => model[key] = '');
        Object.assign(model, res.cmsMemberPage);
        customerInfo(true);
      });
    });
  });
  
  //表单赋值---------------------------------------

  //表单提交-----------------------------------------
  async function handleSubmit() {
    await registerForm.value.validate()
    .then(async () => {
      try {
        setModalProps({ confirmLoading: true });
        let params = Object.assign({}, model);
        await memberUpdate(params).then((res) => {
          if (res.success) {
            $message.createMessage.success(res.message);
            //关闭弹窗
            closeModal();
            emit('success');
          } else {
            $message.createMessage.warning(res.message);
          }
        });
      } finally {
        setModalProps({ confirmLoading: false });
      }
    })
    .catch((error: ValidateErrorEntity<any>) => {
      console.log('error', error);
    });
  }
  // 表单提交-----------------------------------------

  // 同步联系人---------------------------------------
  const [registerCustomerModal, {openModal: openCustomerModal}] = useModal();

  /**
   * 功能描述：1、刷新会员信息；
   *         2、会员信息只关联联系人；
   *
   *  2020-12-15
   * 19622 覃东梁
   */
  function customerInfo(k) {
    var name = model.name;
    var tel  = model.tel
    if (!name) {
      //that.toast('请输入姓名', 'warning')
      return false
    }
    if (!tel) {
      //that.isFocus = true
      return false
    }
    if (tel.length < 11) {
      return false
    }
    if (!(/^1[3456789]\d{9}$/.test(tel))) {
      //如果不是电话号码...（能识别位数、开头是否符合）
      $message.createErrorModal({ title: '错误提示', content: '输入手机号不正确', icon: 'warning'});
      return false
    }

    // uni.showLoading({
    //   title: "匹配中",
    // });
    let params = {
      name: model.name,
      tel: model.tel
    }
    setCustomerInfo(params).then(resp => {
      if (resp.success) {
        count.value = 0
        var lists = resp.result || [];
        if (lists.length == 0) {
          //$message.createMessage.warning('未匹配到客户信息');
          return;
        } else if (lists.length == 1){
          customerInfo2(lists[0])
        } else if (lists.length > 1) {
          count.value = lists.length;
          openCustomerPop(lists, k);
          return;
        }
      } else {
        if (resp.message != '') {
          $message.createMessage.warning(resp.message);
        }
      }
    })

    //uni.hideLoading();
  }

  /**
   * 给表单赋值
   * @param {Object} jsonMap
   */
  function customerInfo2(jsonMap) {
    if (jsonMap && jsonMap.customerId != '' && typeof(jsonMap.customerId) !== 'undefined' && model.name == jsonMap.customerName) {
      if (model.tel == jsonMap.customerLxdh) {
        model.customerTel = jsonMap.customerTel
      } else {
        model.customerTel = '';
      }
      if (model.type == '3') {
        model.areaCode = jsonMap.areaCode
      } else {
        model.areaCode = jsonMap.customerPath
      }
      model.customerId = jsonMap.customerId
      model.areaName   = jsonMap.areaName
      model.corpName   = jsonMap.companyName
      model.departName = jsonMap.departName
      model.path       = jsonMap.customerPath
      model.pathName   = jsonMap.customerPathName
    }
  }

  /**
   * 给表单赋值 , list: list, callback: customerInfo4
   * @param {Object} jsonMap
   */
  function openCustomerPop(lists, k = false) {
    nextTick(() => {
      for (let index = 0; index < lists.length; index++) {
        let jsonMap = lists[index];
        if (jsonMap.customerId == '' || typeof(jsonMap.customerId) == 'undefined') {
          continue;
        }
        if (model.name != jsonMap.customerName || model.tel != jsonMap.customerLxdh) {
          continue;
        }
        customerInfo2(lists[index]);
        break;
      }
      // 有重复数据，且姓名与电话号码有匹配，则不弹出选择框
      if (k) {
        return;
      }
      openCustomerModal(true, {model: {name: model.name, tel: model.tel, customerTel: model.customerTel}, lists: lists});
    });
  }
  // 同步联系人---------------------------------------


  // 搜索公司 ---------------------------------------
  const [registerCompanyModal, {openModal: openCompanyModal}] = useModal();


  // 搜索公司 - 弹出窗口
  function handleCompanySearch() {
    openCompanyModal(true, {isUpdate: true});
  }

  // 会员类型
  function changeModelType() {
    model.areaCode = "";
    model.areaName = "";
    model.corpName = "";
    //Object.assign(model, {});
  }

  // 选择公司 - 会员B
  function changeModelAreaCode(e, o) {
    if (!!o) {
      return false;
    }
    model.corpName = o.label.split('|')[1];
    model.areaName = o.label.split('|')[0];
    registerForm.value.clearValidate();
  }

  //----------------------
  function setSearch(item) {
    let type = item.type || '';
    let areaCode = '', path = '', pathName = '', customerId  = '', customerTel = '';
    let name = '', tel  = '';
    if (type == '1') {
      //选择的是单
      areaCode = item.path;
      path = item.path;
      pathName = item.pathName;
    } else if (type == '2') {
      areaCode = item.areaCode;
      path = item.customerPath;
      pathName = item.customerPathName;
      customerId  = item.customerId; 
      customerTel = item.customerTel; 
      name = item.customerName; 
      tel  = item.customerLxdh;
    } else {
      return false
    }

    if (type == '2' && !areaCode) {
      return false
    }

    if (type == '2' && model.name != name) {
      $message.createErrorModal({ title: '错误提示', content: '姓名不一致无法选择！' });
      return false;
    }
    
    // 
    if (!pathName) {
      return false
    }
    if (!!customerId) {
      model.customerId = customerId;
    }
    if (!!customerTel) {
      model.customerTel = customerTel;
    }

    //清空表单
    model.areaCode = '';
    model.areaName = '';
    model.corpName = '';
    
    var areaName = pathName.split('|')[0];
    var corpName = pathName.split('|')[1];
    model.areaCode = areaCode;
    model.areaName = areaName;
    model.corpName = corpName;

  }
</script>

<style lang="less" scoped>
  #customerTree{ font-family : tahoma ;}
  #customerTree label{ vertical-align : middle ; cursor : pointer }
  #customerTree label:after { content: '\a'; white-space:pre; }
  #customerTree input{ vertical-align : middle ; margin-right : 3px ;}
</style>
